﻿using System;
using System.Drawing;
using System.IO;
using System.Web;

namespace PmfWeb.Core.HttpHandlers
{
    ///<summary>
    /// 在线图片剪切类
    ///</summary>
    public class ImageCropper : IHttpHandler
    {
        /// <summary>
        /// 处理请求
        /// </summary>
        public void ProcessRequest(HttpContext context)
        {
            string pic = Convert.ToString(context.Request["p"]);
            int pointX = Convert.ToInt32(context.Request["x"]);
            int pointY = Convert.ToInt32(context.Request["y"]);
            int cutWidth = Convert.ToInt32(context.Request["w"]);
            int cutHeight = Convert.ToInt32(context.Request["h"]);
            int picWidth = Convert.ToInt32(context.Request["pw"]);
            int picHeight = Convert.ToInt32(context.Request["ph"]);

            context.Response.ContentType = "image/jpeg";
            CutImage(System.Web.HttpContext.Current.Server.MapPath(pic), picWidth, picHeight, pointX, pointY, cutWidth, cutHeight).WriteTo(context.Response.OutputStream);
        }

        /// <summary>
        /// 剪切图片
        /// </summary>
        /// <param name="path">图片路径</param>
        /// <param name="width">图片宽度</param>
        /// <param name="height">图片高度</param>
        /// <param name="pointX">剪切点X坐标</param>
        /// <param name="pointY">剪切点y坐标</param>
        /// <param name="cutWidth">要剪切的宽度</param>
        /// <param name="cutHeight">要剪切的高度</param>
        /// <returns>返回内存流</returns>
        private MemoryStream CutImage(string path, int width, int height, int pointX, int pointY, int cutWidth, int cutHeight)
        {
            Image imgPhoto = Image.FromFile(path);
            Bitmap bmPhoto = new Bitmap(cutWidth, cutHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);

            Graphics gbmPhoto = Graphics.FromImage(bmPhoto);
            gbmPhoto.DrawImage(imgPhoto, new Rectangle(0, 0, cutWidth, cutHeight), pointX * imgPhoto.Width / width, pointY * imgPhoto.Height / height, cutWidth * imgPhoto.Width / width, cutHeight * imgPhoto.Height / height, GraphicsUnit.Pixel);

            MemoryStream ms2 = new MemoryStream();
            bmPhoto.Save(ms2, System.Drawing.Imaging.ImageFormat.Jpeg);

            imgPhoto.Dispose();
            gbmPhoto.Dispose();
            bmPhoto.Dispose();
            return ms2;
        }

        /// <summary>
        /// 其他请求是否可以访问当前对象
        /// </summary>
        public bool IsReusable
        {
            get { return false;}
        }
    }
}
